package com.example.nutritionmate.controller;

import com.example.nutritionmate.dto.DayMealDTO;
import com.example.nutritionmate.entity.User;
import com.example.nutritionmate.service.MealNutritionService;
import com.example.nutritionmate.service.MealService;
import com.example.nutritionmate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Optional;

@RestController
@RequestMapping("/meal")
public class MealController {
    @Autowired
    private MealService mealService;
    @Autowired
    private UserService userService;
    /**
     * 获取当前用户某一天的所有四餐饮食记录。
     *
     * @param userDetails 认证后的用户详情
     * @param date        查询的日期，格式为 YYYY-MM-DD
     * @return            DayMealDTO 包含四餐记录
     */
    @GetMapping("/dayMeals")
    public ResponseEntity<?> getDayMeals(@AuthenticationPrincipal UserDetails userDetails,
                                         @RequestParam String date) {
        // Spring Security 已经确保 userDetails 不为 null
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());

        User user = optionalUser.get();

        LocalDate localDate;
        try {
            localDate = LocalDate.parse(date);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("日期格式错误，正确格式为 YYYY-MM-DD");
        }

        DayMealDTO dayMeal = mealService.getDayMealsByUserAndDate(user, localDate);

        return ResponseEntity.ok(dayMeal);
    }


}
